package com.gdk.ksoft.ui.reporters;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.common.constants.GoodsTypeConstant;
import com.gdk.ksoft.assembly.dbhelper.FreporterDbHelper;
import com.gdk.ksoft.data.entry.tables.CustomerTable;
import com.gdk.ksoft.data.entry.tables.DeliverGoodsTable;
import com.gdk.ksoft.data.entry.tables.SaleGoodsTable;
import com.gdk.ksoft.data.entry.tables.SaleManTable;
import com.gdk.ksoft.data.entry.tables.SaleStatisticsTable;
import com.gdk.ksoft.data.entry.tables.SaleTable;
import com.gdk.ksoft.ui.MainActivity;
import com.gdk.ksoft.ui.reporters.adapters.OrderStatementDetailAdapter;
import com.gdk.ksoft.assembly.dialog.BluetoothPrinterDialog;
import com.gdk.ksoft.assembly.dialog.MessageBox;
import com.gdk.ksoft.assembly.utils.extensions.CanvasUtils;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.DbModelSelector;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.table.DbModel;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.zkc.helper.printer.PrinterClass;

import java.util.HashMap;
import java.util.List;

/**
 * 订单日报详细页面
 */
public class OrderSaleDetailActivity extends Activity {

    @ViewInject(R.id.pordersaleDetail_llOrderInfo)private LinearLayout llOrderInfo;//订单详细信息视图框
    @ViewInject(R.id.pordersaleDetail_txtIcon)private TextView txtIcon;//客户地图图标
    @ViewInject(R.id.pordersaleDetail_txtCustomerName)private TextView txtCustomerName;//客户名称
    @ViewInject(R.id.pordersaleDetail_txtCustomerAddr)private TextView txtCustomerAddr;//客户地址
    @ViewInject(R.id.pordersaleDetail_txtOrderNoTime)private TextView txtOrderNoTime;//开单时间
    @ViewInject(R.id.pordersaleDetail_txtCount)private TextView txtCount;//商品计量
    @ViewInject(R.id.pordersaleDetail_txtKinds)private TextView txtKinds;//商品种类计量
    @ViewInject(R.id.pordersaleDetail_txtMoney)private TextView txtMoney;//金额数
    @ViewInject(R.id.pordersaleDetail_lstOrder)private ListView lstOrder;//商品列表
    @ViewInject(R.id.pOrderSaleDetail_llPrintContainer)private LinearLayout llPrintContainer;//订单打印容器

    private DbUtils dbUtils;//数据库操作对象
    private String orderNo;//订单号
    public HashMap<String,Object> orderInfo = null;//订单信息
    public List<HashMap<String,Object>> goodslist = null;//商品数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_sale_detail);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        Intent intent = getIntent();
        if(intent!=null){
            orderNo = intent.getStringExtra("orderNo");//获取订单单据号
            if(orderNo.startsWith("NO")) llPrintContainer.setVisibility(View.GONE);
            if(!TextUtils.isEmpty(orderNo))//获取订单商品和订单信息
                requestOrderStatementDetail(OrderSaleDetailActivity.this,dbUtils,orderNo);
        }
    }

    /**
     * 页面控件点击事件
     * @param view
     */
    @OnClick(value = {R.id.pOrderSaleDetail_txtPrint,R.id.pordersaleDetail_imgBack})
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.pOrderSaleDetail_txtPrint://打印操作
                showPrintDialog();//打印提示窗口
                break;
            case R.id.pordersaleDetail_imgBack://页面返回
                this.finish();
                overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
                break;
            default:
                break;
        }
    }

    /**
     * 打开链接打印的窗口（打开蓝牙接口，检测打印机状态）
     */
    public void showPrintDialog(){
        if(MainActivity.pl == null || !MainActivity.pl.IsOpen() || MainActivity.pl.getState()!= PrinterClass.STATE_CONNECTED){
            new BluetoothPrinterDialog(this,new BluetoothPrinterDialog.OnBluetoothConnectedListener() {
                @Override
                public void onBluetoothConnected(boolean isSuccessful) {
                    if(isSuccessful){
                        showPrintTipDialog();//选择打印
                    }else{
                        Toast.makeText(OrderSaleDetailActivity.this,"链接打印机失败!",Toast.LENGTH_SHORT).show();
                    }
                }
            }).show();
        }else{
            showPrintTipDialog();//选择打印
        }
    }

    /**
     * 显示打印提示框（选择打印单据一联或者二联）
     */
    public void showPrintTipDialog(){
        final Context context = OrderSaleDetailActivity.this;
        final MessageBox msgBox = new MessageBox(context);
        msgBox.setMessage("请选择你要打印的单据的联数？","一联","二联");
        msgBox.setCanceledOnTouchOutside(false);
        msgBox.setCancelable(false);
        msgBox.setCloseVisiable(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgBox.dismiss();
            }
        });
        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgBox.dismiss();
                switch(v.getId()){
                    case MessageBox.ID_DIALOG_BUTTON_OK:
                        printStatisticsOrder(context,dbUtils,1);//打印一联单据
                        break;
                    case MessageBox.ID_DIALOG_BUTTON_CANCEL:
                        printStatisticsOrder(context,dbUtils,2);//打印二联单据
                        break;
                }
            }
        });
        msgBox.show();
    }

    /**
     * 按一定次数打印订单
     * @param context
     * @param dbUtils
     * @param printCount 订单打印的次数
     */
    public void printStatisticsOrder(final Context context,final DbUtils dbUtils,final int printCount){
        new AsyncTask<Void,Void,Void>(){
            private String errorMessage = null;
            private ProgressDialog dialog = null;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在打印...");

            }
            @Override
            protected Void doInBackground(Void... params) {
                int count = printCount;//获取打印的次数
                while(count>0){
                    try{
                        printOrderList(dbUtils);//开始打印单子
                    }catch (Exception e){
                        errorMessage = e.getMessage();
                        e.printStackTrace();
                        return null;
                    }
                    count--;
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                Toast.makeText(context, errorMessage != null ? "打印失败！原因：" + errorMessage : "打印成功!",
                        Toast.LENGTH_SHORT).show();
            }
        }.execute();
    }

    /**
     * 打印单子
     * @throws Exception
     */
    public void printOrderList(final DbUtils dbUtils)throws Exception{
        SaleTable saleOrderInfo = dbUtils.findFirst(Selector.from(SaleTable.class).where("djh","=",orderNo));
        SaleStatisticsTable statisticsTable = dbUtils.findFirst(Selector.from(SaleStatisticsTable.class).where("djh","=",orderNo));
        List<SaleGoodsTable> saleGoodsList = dbUtils.findAll(Selector.from(SaleGoodsTable.class).where("xsd_id","=",orderNo));
        DbModel dbSaleMan = dbUtils.findDbModelFirst(DbModelSelector.from(SaleManTable.class).select("gsmc", "RealName"));
        DbModel dbCustomer = dbUtils.findDbModelFirst(DbModelSelector.from(CustomerTable.class).where("id", "=", saleOrderInfo.kh_id).select("mc"));
        DbModel dbAddress = dbUtils.findDbModelFirst(DbModelSelector.from(DeliverGoodsTable.class).where("id", "=", saleOrderInfo.shdz_id).select("shdz"));
        String companyName = dbSaleMan.getString("gsmc");//获取业务员公司名称
        final int WIDTH = 840,MARGIN = 5;//纸张宽度和纸张边距
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setTextSize(34f);
        //绘制购货声明
        List<String> strlist = CanvasUtils.breakText(paint, SystemData.SaleDeclare, WIDTH);
        Bitmap bitmap = Bitmap.createBitmap(WIDTH, 700 + 40*(strlist==null?0:strlist.size())
                + 150 * saleGoodsList.size(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        float currentHeight = 0;//纸张当前高度
        paint.reset();
        paint.setAntiAlias(true);
        paint.setTextAlign(Paint.Align.CENTER);//设置文字居中
        paint.setTextSize(45f);
        currentHeight = CanvasUtils.drawText(canvas, paint, companyName + (orderNo.startsWith("XSD") ? "销货清单" : "退货清单"), WIDTH / 2, currentHeight, -1);
        currentHeight = CanvasUtils.drawLine(canvas, paint, 5, currentHeight, WIDTH - 10, 4);
        paint.setTextAlign(Paint.Align.LEFT);
        paint.setTextSize(38f);
        currentHeight = CanvasUtils.drawText(canvas,paint,"客户："+dbCustomer.getString("mc"),MARGIN,currentHeight,-1);
        currentHeight = CanvasUtils.drawText(canvas,paint,"地址："+dbAddress.getString("shdz"),MARGIN,currentHeight,-1);
        currentHeight = CanvasUtils.drawText(canvas,paint,"单号："+orderNo,MARGIN,currentHeight,-1);
        currentHeight = CanvasUtils.drawLine(canvas,paint,5,currentHeight,WIDTH-10,4);
        final String[] columns = {"规格","发价","数量","金额"};
        for(int i=0;i<columns.length;i++){
            float py = CanvasUtils.drawText(canvas,paint,columns[i],MARGIN + i*(WIDTH-10)/columns.length,currentHeight,-1);
            if(i == columns.length-1) currentHeight = py;
        }
        paint.setTextSize(35f);
        for(SaleGoodsTable item : saleGoodsList){//绘制商品列
            String goodsTm = (item.lx == 0?"":"("+ GoodsTypeConstant.getGoodsType().get(item.lx)+")")+item.tm;
            currentHeight = CanvasUtils.drawText(canvas,paint,goodsTm+"  "+item.mc,0,currentHeight,WIDTH/2);
            CanvasUtils.drawText(canvas,paint,item.gg,0,currentHeight,WIDTH/4);
            CanvasUtils.drawText(canvas,paint, "￥"+FormatUtils.exactNumber(item.bzxsdwj/item.hsgx,"0.00"),WIDTH/4,currentHeight,WIDTH/4);
            CanvasUtils.drawText(canvas,paint,(item.xsdwsl==0?"":item.xsdwsl+item.xsdw)+(item.xsdwss==0?"":item.xsdwss+item.hsdw),WIDTH/2,currentHeight,WIDTH/4);
            currentHeight = CanvasUtils.drawText(canvas,paint,"￥"+FormatUtils.exactNumber(item.yfje,"0.00"),3*WIDTH/4,currentHeight,WIDTH/4);
            if(item.bzq!=0) {//如果保质期存在则打印，否则不打印
                CanvasUtils.drawText(canvas,paint,"生产日期："+item.csrq,0,currentHeight,WIDTH/2);
                currentHeight = CanvasUtils.drawText(canvas, paint, "保质期：" + String.valueOf(item.bzq) + "天", WIDTH / 2, currentHeight, WIDTH / 2);
            }
            currentHeight = CanvasUtils.drawLine(canvas,paint,5,currentHeight,WIDTH-10,4);
        }
        paint.setTextSize(38f);
        if(orderInfo!=null) {//获取商品统计信息
            CanvasUtils.drawText(canvas, paint, orderInfo.get("xssl")+"件"+orderInfo.get("xsss")+"散", 0, currentHeight, WIDTH / 3);
            CanvasUtils.drawText(canvas, paint, orderInfo.get("kinds")+"种", WIDTH / 3, currentHeight, WIDTH / 3);
            currentHeight = CanvasUtils.drawText(canvas, paint, "￥"+FormatUtils.exactNumber(orderInfo.get("xssy"),"0.00")+"元", 2 * WIDTH / 3, currentHeight, WIDTH / 3);
        }
        currentHeight = CanvasUtils.drawLine(canvas,paint,5,currentHeight,WIDTH-10,4);
        CanvasUtils.drawText(canvas,paint,"抹零：￥"+FormatUtils.exactNumber(statisticsTable.mlje,"0.00"),0,currentHeight,WIDTH/2);
        currentHeight = CanvasUtils.drawText(canvas, paint, "现金：￥" + FormatUtils.exactNumber(statisticsTable.xjje,"0.00"), WIDTH / 2, currentHeight, WIDTH / 2);
        CanvasUtils.drawText(canvas,paint,"欠款：￥"+FormatUtils.exactNumber(statisticsTable.qkje,"0.00"),0,currentHeight,WIDTH/2);
        currentHeight = CanvasUtils.drawText(canvas, paint, "账期：" + (statisticsTable.zqts > 0? statisticsTable.zqts + "天":""), WIDTH / 2, currentHeight, WIDTH / 2);
        CanvasUtils.drawText(canvas,paint,"银行：￥"+ FormatUtils.exactNumber(statisticsTable.yhje,"0.00"),0,currentHeight,WIDTH/2);
        currentHeight = CanvasUtils.drawText(canvas, paint, "账户：" + (statisticsTable.yhzh.length()>0?statisticsTable.yhzh:""), WIDTH / 2, currentHeight, WIDTH / 2);
        currentHeight = CanvasUtils.drawLine(canvas,paint,5,currentHeight,WIDTH-10,4);
        CanvasUtils.drawText(canvas,paint,"销货人："+dbSaleMan.getString("RealName"),0,currentHeight,-1);
        currentHeight = CanvasUtils.drawText(canvas,paint,"打印时间："+FormatUtils.standardDatetime(new java.util.Date(),"yyyy/MM/dd HH:mm:ss"),
                WIDTH/3,currentHeight,-1);
        currentHeight = CanvasUtils.drawText(canvas,paint,"购货检验人(签字):",0,currentHeight,-1);
        currentHeight = CanvasUtils.drawLine(canvas,paint,5,currentHeight,WIDTH-10,4);
        if(strlist!=null && strlist.size()>0){//销售声明
            paint.setTextSize(34f);
            for(int i=0;i<strlist.size();i++){
                currentHeight = CanvasUtils.drawText(canvas,paint,strlist.get(i),0,currentHeight,WIDTH);
            }
        }
//        FileUtils.writeImageToFile(bitmap, Bitmap.CompressFormat.JPEG, 100, "/sdcard/1.jpg");
        MainActivity.pl.printImage(bitmap);
    }


    /**
     * 获取订单数据
     * @param orderNo 订单号
     */
    public void requestOrderStatementDetail(final Context context,final DbUtils dbUtils,final String orderNo){
        new AsyncTask<Void,Void,Void>(){
            private ProgressDialog dialog = null;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(OrderSaleDetailActivity.this,"","加载中...");
            }
            @Override
            protected Void doInBackground(Void... params) {
                try{
                    orderInfo = FreporterDbHelper.findOrderDetailByOrderNo(dbUtils,orderNo);
                    goodslist = FreporterDbHelper.findAllGoodsByOrderNo(dbUtils,orderNo);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(orderInfo!=null){
                    txtIcon.setText(orderInfo.get("kico").toString());
                    txtCustomerName.setText(orderInfo.get("kmc").toString());
                    txtCustomerAddr.setText("联系地址："+orderInfo.get("kaddr").toString());
                    txtOrderNoTime.setText("开单时间："+orderInfo.get("kdsj").toString());
                    txtCount.setText(orderInfo.get("xssl")+"件"+orderInfo.get("xsss")+"散");
                    txtKinds.setText(orderInfo.get("kinds")+"种");
                    txtMoney.setText(FormatUtils.exactNumber(orderInfo.get("xssy"),"0.00")+"元");
                }else{
                    llOrderInfo.setVisibility(View.GONE);
                }
                if(goodslist!=null){//获取商品列表
                    lstOrder.setAdapter(new OrderStatementDetailAdapter(context,goodslist));
                }
            }
        }.execute();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
            overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
